//
//  HWParagraphString.m
//  ParagraphString
//
//  Created by Lucy_Lee on 2017/1/18.
//  Copyright © 2017年 Lucy_Lee. All rights reserved.
//

#import "HWParagraphString.h"

@interface HWParagraphString ()

@property (nonatomic, strong, readwrite) NSMutableAttributedString * attributedString;

@end

@implementation HWParagraphString

#pragma mark --config for string
-(void)makeConfigEffective{
    
    if (!self.string) {
        self.attributedString = nil;
        return;
    }
    NSRange range = NSMakeRange(0, self.string.length);
    NSMutableAttributedString * richString = [[NSMutableAttributedString alloc]initWithString:self.string];
    self.font ? [richString addAttribute:NSFontAttributeName value:self.font range:range] : 0;
    self.textColor ? [richString addAttribute:NSForegroundColorAttributeName value:self.textColor range:range] :0;
    self.paragraphStyle ? [richString addAttribute:NSParagraphStyleAttributeName value:self.paragraphStyle range:range] : nil;
    self.attributedString = richString;
}

#pragma mark --constructor
+ (instancetype)paragraphStringWithString:(NSString *)string font:(UIFont *)font color:(UIColor *)color paragraphStyle:(NSMutableParagraphStyle *)style{

    HWParagraphString * paragraphString = [[[self class] alloc] init];
    paragraphString.string = string;
    paragraphString.font = font;
    paragraphString.textColor = color;
    paragraphString.paragraphStyle = style;
    [paragraphString makeConfigEffective];
    return paragraphString;
}

#pragma mark --string's height with the fixed width
- (CGFloat)heightWithFixedWidth:(CGFloat)width{
    CGFloat height = 0;
    if (self.attributedString) {
        CGRect rect = [self.attributedString boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil];
        height = rect.size.height;
    }
    return height;
}

#pragma mark --The string's height with the fixed width.
- (CGFloat)numberOfLines:(NSInteger)lines fixedWidth:(CGFloat)width{
    
    NSRange range = NSMakeRange(0, self.string.length);
    NSMutableAttributedString * richString = [[NSMutableAttributedString alloc]initWithString:self.string];
    self.font ? [richString addAttribute:NSFontAttributeName value:self.font range:range] : 0;
    self.textColor ? [richString addAttribute:NSForegroundColorAttributeName value:self.textColor range:range] :0;
    self.paragraphStyle ? [richString addAttribute:NSParagraphStyleAttributeName value:self.paragraphStyle range:range] : nil;
    UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, width, 0)];
    label.numberOfLines = lines;
    label.attributedText = richString;
    [label sizeToFit];
    return label.frame.size.height;
}

@end
